// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <pollux/common/memory/memory.h>
#include <pollux/functions/remote/if/gen-cpp2/RemoteFunctionService.h>
#include <pollux/vector/vector_stream.h>

namespace kumo::pollux::exec {
    class EvalErrors;
}

namespace kumo::pollux::functions {
    // Simple implementation of the thrift server handler.
    class RemoteFunctionServiceHandler
            : virtual public apache::thrift::ServiceHandler<
                remote::RemoteFunctionService> {
    public:
        RemoteFunctionServiceHandler(
            const std::string &functionPrefix = "",
            std::shared_ptr<memory::MemoryPool> pool = nullptr)
            : functionPrefix_(functionPrefix), pool_(std::move(pool)) {
            if (pool_ == nullptr) {
                pool_ = memory::memoryManager()->addLeafPool();
            }
        }

        void invokeFunction(
            remote::RemoteFunctionResponse &response,
            std::unique_ptr<remote::RemoteFunctionRequest> request) override;

    private:
        /// Add evalErrors to result by serializing them to a vector of strings and
        /// converting the result to a Pollux flat vector.
        void handleErrors(
            apache::thrift::field_ref<remote::RemoteFunctionPage &> result,
            exec::EvalErrors *evalErrors,
            const std::unique_ptr<VectorSerde> &serde) const;

        const std::string functionPrefix_;
        std::shared_ptr<memory::MemoryPool> pool_;
    };
} // namespace kumo::pollux::functions
